<template>
  <div ref="mainCon" class="container">
    <topTitle :titleText="titleText"></topTitle>
    <div class="mainCon" ref="mainCon">
      <el-row class="toolbar searchInputWidth" style="padding-bottom: 0">
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <el-col :lg="8" :xl="6">
            <el-form-item
              label="区域"
              class="row-padding-bottom"
              v-if="authQyXmFlag"
            >
              <el-cascader
                ref="manageArea"
                v-model="areaArr"
                :options="areasOptions"
                @change="getAreaId"
                clearable
                filterable
                :props="{ checkStrictly: true }"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="整改状态" class="row-padding-bottom">
              <el-select
                v-model="filterField.status"
                clearable
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="(item, index) of statusData"
                  :key="index"
                  :label="item.name"
                  :value="item.code"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="advanced">
            <el-col :lg="8" :xl="6">
              <el-form-item label="工程项目" class="row-padding-bottom">
                <el-input
                  v-model="filterField.project"
                  placeholder="输入项目名称"
                  clearable
                  class="scopeInputWidth"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <!-- <div style="display: inline-block">
                <div style="display: inline-block;" v-if="isBigScreen" > -->
              <el-form-item
                label="创建人"
                class="row-padding-bottom"
                v-if="authQyXmFlag"
              >
                <el-input
                  v-model="filterField.user"
                  placeholder="输入姓名或用户名搜索"
                  clearable
                  class="scopeInputWidth"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item
                label="行业"
                class="row-padding-bottom"
                v-if="authQyXmFlag"
              >
                <el-select
                  v-model="filterField.industryId"
                  filterable
                  placeholder="请选择"
                  clearable
                  class="scopeInputWidth"
                >
                  <el-option
                    v-for="item in industryOptions"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item
                label="用工单位"
                class="row-padding-bottom"
                v-if="authQyXmFlag"
              >
                <el-input
                  v-model="filterField.mainName"
                  placeholder="输入单位名称"
                  clearable
                  class="scopeInputWidth"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <!-- </div> -->
              <!-- <div style="display: inline-block" v-if="isBigScreen"> -->
              <el-form-item
                label="问题类型"
                class="row-padding-bottom problemSelect"
                v-if="authQyXmFlag"
              >
                <el-select
                  v-model="filterField.ids"
                  filterable
                  placeholder="请选择"
                  multiple
                  clearable
                >
                  <el-option
                    v-for="(item, index) in problemList"
                    :key="item.id"
                    :label="item.reason"
                    :value="item.schemeId"
                  ></el-option>
                  <!--<el-tooltip placement="bottom" v-for="(item,index) in problemList" :key="item.id">
                                <div slot="content">
                                    <div :style="{maxWidth:'200px', wordBreak: 'break-all'}">{{item.reason}}</div>
                                </div>
                                <el-option  :label="item.name" :value="item.id"></el-option>
                            </el-tooltip>-->
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item
                label="创建时间"
                class="row-padding-bottom"
                v-if="authQyXmFlag"
              >
                <el-date-picker
                  v-model="date"
                  type="daterange"
                  unlink-panels
                  :picker-options="pickerOptions"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <!-- <el-col :lg="8" :xl="6"> -->
            <!-- </div> -->
            <!-- <el-form-item class="row-padding-bottom" v-if="authQyXmFlag">
                        <div class="openBtn" @click="isBigScreen = !isBigScreen">{{isBigScreen?'收起':'展开'}}&nbsp;<i class="el-icon-arrow-down" :class="[isBigScreen?  'down' : 'up' ]"></i></div>
                </el-form-item>
                </el-col> -->
          </template>
          <el-form-item class="row-padding-bottom">
            <a
              @click="toggleAdvanced"
              style="margin-left: 40px; color: #409eff; cursor: pointer"
              class="btnColor"
            >
              {{ advanced ? '收起' : '展开' }}
              <i
                :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
              ></i>
            </a>
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchList"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
            <!-- <el-button type="primary" icon="icon iconfont iconchazhao1" @click="searchList"
                                   class="commonBtn"></el-button> -->
          </el-form-item>
          <!-- </div> -->
        </el-form>
      </el-row>

      <div class="spacing"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <div class="searchTableActions">
          查询表格
          <div class="fr">
            <div class="loadBtn" v-if="authQyXmFlag">
              <div class="btnBox">
                <el-button
                  class="commonBut saveBtn funComBut"
                  @click="showFileFlag = !showFileFlag"
                >
                  下载建议书<i
                    class="el-icon--right"
                    :class="[
                      showFileFlag
                        ? 'el-icon-caret-top'
                        : 'el-icon-caret-bottom',
                    ]"
                  ></i
                ></el-button>
                <ul v-if="showFileFlag">
                  <li @click="selectPdf(true)">导出为PDF</li>
                  <li @click="selectPdf(false)">导出为word</li>
                </ul>
              </div>
            </div>
            <el-button
              class="commonBut saveBtn funComBut"
              @click="addProposal"
              v-if="authQyXmFlag"
            >
              <i class="el-icon-circle-plus-outline"></i> 新建建议书
            </el-button>
          </div>
        </div>
        <el-table
          :data="tableList"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          style="border: 1px solid #dfe6ec"
          header-cell-class-name="tableHeaderName"
          highlight-current-row
          :row-key="recordId"
          :max-height="tableHeight"
          @select="checkData"
          @select-all="checkDataAll"
          @sort-change="sortChange"
        >
          <el-table-column
            type="selection"
            width="50"
            :reserve-selection="true"
            v-if="authQyXmFlag"
          ></el-table-column>
          <el-table-column
            prop="areaName"
            label="区域"
            width="100"
          ></el-table-column>
          <el-table-column prop="industryName" label="行业"></el-table-column>
          <el-table-column prop="mainName" label="用工单位" width="230">
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.mainName"
                :columnName="'mainName'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column prop="projectName" label="工程项目" width="230">
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.projectName"
                :columnName="'projectName'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            prop="problem"
            sortable="custom"
            label="用工问题"
            width="120"
          >
            <template slot-scope="scope">
              <span>{{ scope.row.problem }}个</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="statusStr"
            label="建议书状态"
            width="120"
          ></el-table-column>
          <el-table-column prop="userName" label="建议书创建人" width="150">
            <template slot-scope="scope">
              <span>({{ scope.row.nickName }}){{ scope.row.userName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            sortable="custom"
            label="创建时间"
            width="170"
          ></el-table-column>
          <el-table-column label="操作" align="left" fixed="right" width="130">
            <template slot-scope="scope">
              <el-link type="primary" @click="toDetail(scope.row)"
                >查看</el-link
              >
              <el-link
                type="primary"
                @click="toDelete(scope.row)"
                v-if="authQyXmFlag"
                >删除</el-link
              >
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关数据"></emptyTable>
          </div>
        </el-table>
      </div>
      <!-- getTableList为获取子组件的数据 -->
      <Pagination
        ref="pagination"
        @getList="getTableList"
        :filterField="filterField"
        :requestUrl="requestUrl"
      ></Pagination>
    </div>
  </div>
</template>

<script>
import topTitle from '@/components/publicCom/topTitle'
import emptyTable from '@/components/publicCom/emptyTable'
import Pagination from '@/components/publicCom/newPagination'
import scrollTable from '@/mixin/scrollTable.js'
export default {
  name: 'proposal',
  mixins: [scrollTable],
  components: {
    emptyTable,
    Pagination,
    topTitle,
  },
  data() {
    return {
      titleText: '建议书',
      statusData: [
        { name: '全部状态', code: '' },
        { name: '待企业整改', code: 'WAIT' },
        { name: '企业整改中', code: 'DOING' },
        { name: '整改完成', code: 'DONE' },
      ], //整改状态
      areasOptions: [], //区域
      areaArr: [],
      industryOptions: [], //行业
      //表格数据
      tableList: [
        /*{
          areaName: '武汉市', industryName: '交通',
          mainName: '湖北会基科技有限公司', projectName: '广州机场拓建工程二号航站及配套设施',
          problem: '3个', status: '待企业整改', founder: '张三（hdmin', createTime: '2020-12-11 19:50:00'
        },
          {
            areaName: '武汉市', industryName: '交通',
            mainName: '湖北会基科技有限公司', projectName: '广州机场拓建工程二号航站及配套设施',
            problem: '3个', status: '待企业整改', founder: '张三（hdmin', createTime: '2020-12-11 19:50:00'
          }*/
      ],
      requestUrl: 'api-ps/enforce/proposal/list',

      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
      },
      date: [], //日期区间
      //搜索条件
      filterField: {
        areaId: '', //区域
        industryId: '', //行业
        status: '', //状态
        project: '', //项目名称
        ids: [], //问题类型
        mainName: '', //用工单位
        user: '', //创建人
        start: '',
        end: '',
      },
      companyId: '', //跳转详情传参
      isShow: true, //列表加载
      loading: true,
      // isBigScreen: false,
      checkedId: [], //列表选中id数组
      checkedProject: [], //列表选中id数组
      problemList: [
        //问题类型
      ],
      showFileFlag: false, //显示下载类型
      authQyXmFlag: true,
      loginType: '',
      advanced: false,
    }
  },
  created() {
    //获取行业
    this.getIndustry()
    //获取区域
    this.getArea()
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    this.getProblem()
    this.loginType = localStorage.getItem('loginType')
    if (this.loginType === 'QY' || this.loginType === 'XM') {
      this.authQyXmFlag = false
    }
  },
  methods: {
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    dataSearch(val) {
      console.log(val, typeof val)
      this.filterField.start = val[0]
      this.filterField.end = val[1]
    },
    // pdf true or false
    selectPdf(pdf) {
      this.showFileFlag = false
      if (this.checkedId.length === 0) {
        this.$message({
          message: '请选择建议书！',
          type: 'error',
        })
        return
      }
      const loading = this.$loading({
        lock: true, //lock的修改符--默认是false
        text: '', //显示在加载图标下方的加载文案
        spinner: 'el-icon-loading', //自定义加载图标类名
        background: 'rgba(0, 0, 0, 0.7)', //遮罩层颜色
        target: document.querySelector('body'), //loadin覆盖的dom元素节点
      })
      let dt = new Date()
      let ymd =
        dt.getFullYear() + '.' + (dt.getMonth() + 1) + '.' + dt.getDate()
      let fileName = '建议书_' + ymd + '.zip'
      let url = 'api-ps/enforce/proposal/select/pdf'
      let data = {
        ids: this.checkedId,
        pdf: pdf,
      }
      if (this.checkedId.length === 1) {
        fileName =
          '建议书_' +
          this.checkedProject[0] +
          '_' +
          ymd +
          (pdf ? '.pdf' : '.docx')
        url = 'api-ps/enforce/proposal/single/pdf'
        data = {
          id: this.checkedId[0],
          pdf: pdf,
        }
      }
      this.axios({
        method: 'post',
        url: url,
        data: data,
        responseType: 'blob',
      })
        .then((res) => {
          console.log(res)
          loading.close()
          if (res && res.data.type === 'application/json') {
            let msg = '下载出错了，请稍候重试！'
            if (res.data.msg) {
              msg = res.data.msg
            }
            this.$message({
              message: msg,
              type: 'error',
            })
            return
          }
          const content = res.data
          const blob = new Blob([content])
          if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
        })
        .catch((error) => {
          console.log(error)
          loading.close()
        })
    },
    getIndustry() {
      const that = this
      this.axios({
        method: 'get',
        url: 'api-bs/base/dicitem/getuserindustry',
      })
        .then((res) => {
          if (res && res.data) {
            that.industryOptions = res.data.result
          }
        })
        .catch((error) => {
          that.$message({
            showClose: true,
            duration: 3000,
            message: '获取行业数据失败',
            type: 'error',
          })
        })
    },
    // 获取区域数据
    getArea() {
      const that = this
      let areaId = localStorage.getItem('areaId')
      this.axios({
        method: 'get',
        url: 'api-bs/areadic/base/detailbyareaid',
        params: { areaId: areaId },
      })
        .then((res) => {
          if (res && res.data) {
            that.areasOptions = res.data.result
          }
        })
        .catch((error) => {
          that.$message({
            showClose: true,
            duration: 3000,
            message: '获取行业数据失败',
            type: 'error',
          })
        })
    },
    getProblem() {
      console.log('getProblem')
      const that = this
      this.axios({
        method: 'get',
        url: 'api-ps/enforce/problem/all/y',
      })
        .then((res) => {
          if (res && res.data) {
            that.problemList = res.data.result
          }
        })
        .catch((error) => {
          that.$message({
            showClose: true,
            duration: 3000,
            message: '获取问题类型失败',
            type: 'error',
          })
        })
    },
    //获取选中的区域最后一级id
    getAreaId() {
      this.filterField.areaId = this.areaArr[this.areaArr.length - 1]
    },
    getTableList(data) {
      this.tableList = data.results || []
      this.loading = false
      if (this.tableList.length < 1) {
        this.isShow = true
      }
    },
    // 搜索
    searchList() {
      this.loading = true

      if (this.date) {
        this.filterField.start = this.date[0]
        this.filterField.end = this.date[1]
      } else {
        this.filterField.start = ''
        this.filterField.end = ''
      }
      this.$refs.pagination.getTableListData()
    },
    recordId(row) {
      return row.id
    },
    //列表多选选中事件
    checkData(selection, row) {
      var selected = selection.length && selection.indexOf(row) !== -1
      if (selected) {
        this.checkedId.push(row.id)
        this.checkedProject.push(row.projectName)
      } else {
        this.checkedId.forEach((item, i) => {
          if (item === row.id) {
            this.checkedId.splice(i, 1)
            this.checkedProject.splice(i, 1)
          }
        })
      }
    },
    checkDataAll(selection) {
      console.log(selection)
      this.checkedId = []
      this.checkedProject = []
      var selected = selection.length
      if (selected) {
        selection.forEach((row) => {
          this.checkedId.push(row.id)
          this.checkedProject.push(row.projectName)
        })
        console.log(this.checkedId)
        console.log(this.checkedProject)
      }
    },
    //新建建议书
    addProposal() {
      this.$router.push({
        path: '/home/onlineLaw/addProposal',
        name: 'addProposal',
      })
      this.$store.commit('CHANGE_PROPOSAL_DATA', {})
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/onlineLaw/proposal',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    //建议书详情
    toDetail(row) {
      this.$router.push({
        path: '/home/onlineLaw/detailProposal',
        query: { id: row.id },
        name: 'detailProposal',
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/onlineLaw/proposal',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    toDelete(row) {
      this.$alert('是否删除该建议书', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        this.axios({
          method: 'post',
          url: 'api-ps/enforce/proposal/delete',
          data: { id: row.id },
        })
          .then((resp) => {
            this.$refs.pagination.getTableListData()
            this.$message({
              type: 'success',
              message: '删除成功!',
            })
          })
          .catch((resp) => {
            console.log('请求失败：' + resp.status + ',' + resp.statusText)
          })
      })
    },
  },
}
</script>

<style lang="less" scoped>
.mainCon {
  top: 198px;
  // .toolbar {
  //     margin-bottom: 20px !important;

  // }
  // .poposalInputWidth{
  //     .problemSelect {
  //        /deep/ .el-form-item__content {
  //             height: auto !important;

  //         }

  //     }

  //     /deep/ .el-input__inner{
  //         width: 200px;
  //     }
  //     /deep/ .el-range-editor.el-input__inner {
  //         width: 230px;
  //     }
  //     /deep/ .el-range-separator {
  //         width: 8%;
  //     }
  // }

  .loadBtn {
    display: inline-block;
    .btnBox {
      position: relative;
      width: 100%;

      ul {
        width: 100%;
        position: absolute;
        top: 45px;
        max-height: 274px;
        background: #fff;
        padding: 6px 0;
        margin: 0;
        box-shadow: 0 0 8px #ddd;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        border-radius: 4px;
        z-index: 100;
        &::after {
          position: absolute;
          content: '';
          left: 27px;
          top: -6px;
          border-width: 0 6px 6px 6px;
          border-style: solid;
          border-color: transparent transparent #fff transparent;
        }

        li {
          width: 100%;
          color: #606266;
          height: 34px;
          line-height: 34px;
          text-align: center;
          font-size: 14px;
          -webkit-box-sizing: border-box;
          box-sizing: border-box;
          cursor: pointer;

          &:hover {
            color: #409eff;
            font-weight: 700;
          }
        }
      }
    }
  }

  @media screen and (min-width: 1280px) and (max-width: 1366px) {
    .poposalInputWidth /deep/.el-form-item__label {
      width: 56px;
    }
  }

  .openBtn {
    padding: 0 6px 0 10px;
    color: #409eff;
    .down {
      -webkit-transform: rotate(180deg);
      transition: all 0.3s;
      vertical-align: 0;
    }

    .up {
      -webkit-transform: rotate(0deg);
      transition: all 0.3s;
      vertical-align: -1px;
    }
  }

  /deep/ .el-icon-circle-plus-outline {
    font-size: 16px;
    font-weight: bold;
    vertical-align: -1px;
  }
}
</style>
<!--<style lang="less">-->
<!--  .tableHeaderName:first-child {-->
<!--  .cell {-->
<!--    display: none;-->
<!--  }-->
<!--  }-->
<!--</style>-->
